package com.example.cloudapirabbitmq.direct;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class RabbitMQConsumer {

    @RabbitListener(queues = "order.queue")
    public void handleMessage(Message message, Channel channel) throws IOException {
        String msgId = message.getMessageProperties().getMessageId();
        try {
            // 业务逻辑（模拟失败场景）
            String content = new String(message.getBody());
            if (content.contains("error")) {
                throw new RuntimeException("模拟处理失败");
            }
            log.info("消息消费成功，ID：{}", msgId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); // 手动ACK
        } catch (Exception e) {
            log.error("消息消费失败，ID：{}，重试次数：{}", msgId, getRetryCount(channel, message));
            if (getRetryCount(channel, message) >= 2) { // 最后一次重试后拒绝并进入死信队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); // 重试
            }
        }
    }

    // 获取当前重试次数（通过消息头记录）
    private int getRetryCount(Channel channel, Message message) {
        Integer retryCount = (Integer) message.getMessageProperties().getHeaders().get("retryCount");
        return retryCount == null ? 0 : retryCount + 1;
    }
}